import React from 'react';
import {
    Layout,
    Card,
    Button,
    Table,
    Space,
    Tabs,
    Modal,
    Form,
    DatePicker,
    TimePicker,
    Select,
    Input,
    message,
    Popconfirm
} from 'antd';
import moment from 'moment';
import { API } from '../net/api';
import {roomInfos} from '../roomInfo'
import "antd/dist/antd.css";
import './Main.css';


const {Content} = Layout;
const {TabPane} = Tabs;
const {Option} = Select;
const timeFormat = 'HH:mm';


class Main extends React.Component {


    formRef = React.createRef();

    constructor(props) {
        super(props);
        this.columns = [
            {
                title: '序号',
                render: (text, record, index) => `${index + 1}`,
            },
            {
                title: 'ID',
                dataIndex: 'id',
                key: 'id',
                className:'hidden'
            },
            {
                title: '房间名',
                dataIndex: 'roomName',
                key: 'roomName',
            },
            {
                title: '开始',
                dataIndex: 'startTime',
                key: 'startTime',
            },
            {
                title: '结束',
                dataIndex: 'endTime',
                key: 'endTime',
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <Space size="middle">
                        <Button type="primary" size={"small"} onClick={() => this.editBookInfo(record)}>编辑</Button>
                        <Popconfirm title="确定删除吗?" onConfirm={() => this.deleteBookInfo(record.id)}>
                            <Button type="danger" size={"small"}>删除</Button>
                        </Popconfirm>

                    </Space>
                ),
            },
        ];
        this.state = {
            isLoaded: false,
            visible: false,
            tabKey: 0,
            availableTimeLoading: false,
            availableTime: '请先选择日期和房间',
        }
    }

    tabChange = (activeKey) =>{
        this.setState({
            tabKey: activeKey,
        });
    };

    addBookInfo = () => {
        this.setState({
            visible: true,
        });
    };
    editBookInfo = async row => {
        await this.setState({
            visible: true,
        });
        const values = {
            date: moment(row.date, "YYYY-MM-DD"),
            roomId: row.roomId,
            startTime: moment(row.startTime, 'HH:mm'),
            endTime: moment(row.endTime, 'HH:mm'),
            bookInfoId: row.id,
            submitType: 'modify',
        };
        this.formRef.current.setFieldsValue(values);
        this.updateRemainTime(values, values)
    };
    deleteBookInfo = id => {
        let _this = this;
        API('deleteBookInfo',{
            bookInfoId: id,
        }).then(res=>{
            if (res.retcode === "0000") {
                message.success('删除成功');
                _this.getBookInfo();
            } else {
                message.error(res.errorMsg);
            }
        });
    };

    submitModal = () => {
        let _this = this;
        API('submitBookInfo',{
            date: this.formRef.current.getFieldValue('date').format('YYYY-MM-DD'),
            roomId: this.formRef.current.getFieldValue('roomId'),
            startTime: this.formRef.current.getFieldValue('startTime').format('HH:mm:ss'),
            endTime: this.formRef.current.getFieldValue('endTime').format('HH:mm:ss'),
            bookInfoId: this.formRef.current.getFieldValue('bookInfoId'),
            submitType: this.formRef.current.getFieldValue('submitType')
        }).then(res=>{
            if (res.retcode === "0000") {
                message.success('提交成功');
                _this.formRef.current.resetFields();
                _this.setState({
                    visible: false,
                });
                _this.getBookInfo();
            } else {
                message.error(res.errorMsg);
            }
        });
    };

    closeModal = () => {
        this.setState({availableTime: '请先选择日期和房间'});
        this.formRef.current.resetFields();
        this.setState({
            visible: false,
        });
    };


    componentDidMount() {
        this.getBookInfo()
    }

    getBookInfo = () => {
        let _this = this;
        _this.setState({isLoaded: false});
        API('getBookInfo',{
            id: '51184501028',
            pwd: 'Lin1230!'
        }).then(res=>{
            _this.setState({bookInfos: res.data, isLoaded: true});
        })
    };

    updateRemainTime = (changedValues, allValues) => {
        if (allValues.roomId === '' || allValues.date === '') {
            this.setState({availableTime: '请先选择日期和房间'});
        } else {
            if (changedValues.hasOwnProperty('date') || changedValues.hasOwnProperty('roomId')) {
                this.setState({availableTimeLoading: true});
                let _this = this;
                API('getRoomInfo', {
                    roomId: allValues.roomId,
                    date: allValues.date.format('YYYY-MM-DD'),
                    bookInfoId: allValues.bookInfoId,
                    submitType: allValues.submitType
                }).then(res => {
                    let roomInfoWithTime = res.data;
                    if (roomInfoWithTime.remainTime.length === 0) {
                        _this.setState({availableTime: '这个房间被预定完了'});
                    } else {
                        let remainTime = '';
                        roomInfoWithTime.remainTime.forEach(function (ele) {
                            remainTime += ele.startTime + '~' + ele.endTime + ' | ';
                        });
                        remainTime = remainTime.substring(0, remainTime.length - 3);
                        _this.setState({availableTime: remainTime});
                    }
                    _this.setState({availableTimeLoading: false});
                });
            }
        }
    };


    render() {
        if (!this.state.isLoaded) {
            return (
                <Content className="site-layout" style={{padding: '0 50px', marginTop: 64}}>
                    loading
                </Content>)
        } else {
            return (
                <Content className="site-layout" style={{padding: '40px 50px 0 50px', marginTop: 64}}>
                    <div className="site-layout-background" style={{padding: 24, minHeight: 380}}>
                        <Card title="已有预定" extra={<Button type="primary" onClick={this.addBookInfo}>新增预定</Button>}>
                            <Tabs defaultActiveKey={this.state.tabKey}  onChange={this.tabChange}>
                                {Object.keys(this.state.bookInfos).map((obj, idx) => (
                                    <TabPane tab={obj} key={idx}>
                                        <Table rowKey={row => row.id} dataSource={this.state.bookInfos[obj]}
                                               columns={this.columns}/>
                                    </TabPane>
                                ))}
                            </Tabs>
                        </Card>
                    </div>
                    <Modal
                        title="预定提交"
                        visible={this.state.visible}
                        width='700px'
                        onOk={this.submitModal}
                        onCancel={this.closeModal}
                    >
                        <Form ref={this.formRef}
                              initialValues={{
                                  bookInfoId: 0,
                                  submitType: 'create',
                                  date: '',
                                  roomId: '',
                                  availableTime: '请先选择日期和房间',
                                  startTime: '',
                                  endTime: '',
                              }}
                              wrapperCol={{span: 14}}
                              onValuesChange={this.updateRemainTime}>
                            <Form.Item label="预定日期" name="bookInfoId" style={{display: 'none'}}>
                                <Input name="bookInfoId" type="hidden"/>
                            </Form.Item>
                            <Form.Item label="预定日期" name="submitType" style={{display: 'none'}}>
                                <Input name="submitType" type="hidden"/>
                            </Form.Item>

                            <Form.Item label="预定日期" name="date">
                                <DatePicker placeholder="选择日期" disabledDate={current => {
                                    let now = moment();
                                    const tooLate = current.diff(now, 'hours') > 5 * 24;
                                    const tooEarly = now.diff(current, 'hours') >= 0;
                                    return tooEarly || tooLate;
                                }}/>
                            </Form.Item>

                            <Form.Item label="预定房间" name="roomId">
                                <Select placeholder="选择预定房间" style={{width: 220}}>
                                    {roomInfos.map((obj, idx) => (
                                        <Option key={idx} value={obj.roomId}>{obj.roomName}</Option>
                                    ))}
                                </Select>
                            </Form.Item>

                            <Form.Item label="可选时间" name="availableTime">
                                <span>{this.state.availableTime}</span>
                            </Form.Item>

                            <Form.Item label="预定时间" style={{marginBottom: 0}}>
                                <Form.Item style={{display: 'inline-block'}} name="startTime">
                                    <TimePicker placeholder="选择开始时间" format={timeFormat} disabledHours={() => {
                                        return [0, 1, 2, 3, 4, 5, 6, 7, 23, 24]
                                    }} minuteStep={30} hideDisabledOptions/>
                                </Form.Item>
                                <span
                                    style={{
                                        display: 'inline-block',
                                        width: '24px',
                                        lineHeight: '32px',
                                        textAlign: 'center'
                                    }}
                                >-</span>
                                <Form.Item style={{display: 'inline-block'}} name="endTime">
                                    <TimePicker placeholder="选择结束时间" format={timeFormat} disabledHours={() => {
                                        return [0, 1, 2, 3, 4, 5, 6, 7, 23, 24]
                                    }} minuteStep={30} hideDisabledOptions/>
                                </Form.Item>
                            </Form.Item>

                        </Form>
                    </Modal>
                </Content>);
        }

    }
}


export default Main;
